import { _decorator, Component, Node, Button, Label, Sprite } from 'cc';
import { BasePanel } from '../../../../scripts/libs/ui/BasePanel';
import { udm } from '../../../../scripts/managers/UserDataManager';
import { MergeASAP } from '../../../../scripts/libs/rxjs/cc3/Merge';
import { gm } from '../../../../scripts/managers/GameManager';
import { Observable, of, Subscription } from 'rxjs';
import { nullifySubscription } from '../../../../scripts/libs/rxjs/utils';
import { ReactiveProperty } from '../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { StringTools } from '../../../../scripts/libs/utils/StringTools';
import { TweenToStart } from '../../../../scripts/libs/rxjs/cc3/TweenStart';
import { MSResolve, MSRToString_th_m_s_2, MSRToString_tm_s } from '../../../../scripts/libs/utils/date';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { SettingsPanel } from '../SettingsPanel/SettingsPanel';
import { IntervalStartNow } from '../../../../scripts/libs/rxjs/cc3/CreatorSchedule';
import { lm } from '../../LobbyManager';
import { ShopPanel } from '../ShopPanel/ShopPanel';
import { BuyHeartPanel } from '../BuyHeartPanel/BuyHeartPanel';
import { pfm } from '../../../../scripts/managers/PlayFabManager';
import { FlowStatus } from '../../Enums';
import { UIOpacity } from 'cc';
import { linear, linearClamp } from '../../../../scripts/libs/utils/math';
import { nc } from '../../../../scripts/libs/rxjs/NotificationCenter';
import { Animation } from 'cc';
import { AnimationPlay } from '../../../../scripts/libs/rxjs/cc3/AnimationPlay';
import { v3 } from 'cc';
import { Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ResourcePanel')
export class ResourcePanel extends BasePanel {

    @property(Node)
    topNode: Node = null;

    @property(Button)
    settingsButton: Button = null;

    @property(Label)
    heartCountLabel: Label = null;

    @property(Label)
    coinCountLabel: Label = null;

    coinValue = ReactiveProperty.Create(0);

    // @property(Label)
    // itemsLabel: Label = null;

    @property(Label)
    noAdsLabel: Label = null;

    @property(Button)
    heartButton: Button = null;

    @property(Label)
    heartValueLabel: Label = null;

    @property(Node)
    heartPlusNode: Node = null;

    @property(Node)
    infHeartIconNode: Node = null;

    @property(Button)
    coinButton: Button = null;

    @property(Label)
    accountInfoLabel: Label = null;

    @property(Node)
    buttonsNode: Node = null;

    @property(Sprite)
    coinIconSprite: Sprite = null;

    willBind(): void {
        this.adaptive();
    }

    useObserves() {
        return [
            MergeASAP(udm.heart, gm.heartAnimatingFlags, udm.infHeartTill).subscribe(this.refreshHeart.bind(this)),
            MergeASAP(udm.coin, gm.coinAnimatingFlags, udm.temp_coin_diff).subscribe(this.refreshCoinTarget.bind(this)),
            // MergeASAP(udm.itemSwapper, udm.itemMagnet, udm.itemBalloon, gm.itemAnimatingFlags).subscribe(this.refreshItems.bind(this)),
            MergeASAP(udm.noAds, udm.noAdsUntil).subscribe(this.refreshNoAds.bind(this)),
            IntervalStartNow(1, this.node).subscribe(_ => {
                this.refreshHeart();
                this.refreshNoAds();
            }),
            this.coinValue.subscribe(this.refreshCoin.bind(this)),

            BindButton(this.settingsButton).subscribe(this.settingsButtonClicked.bind(this)),
            BindButton(this.heartButton).subscribe(this.heartButtonClicked.bind(this)),
            BindButton(this.coinButton).subscribe(this.coinButtonClicked.bind(this)),

            MergeASAP(lm.shopPanelOpened, lm.dailyTaskPanelOpened, lm.luckyWheelPanelOpened).subscribe(_ => {
                if (lm.shopPanelOpened.value || lm.dailyTaskPanelOpened.value || lm.luckyWheelPanelOpened.value) this.node.setSiblingIndex(-1);
            }),
            MergeASAP(udm.displayName, pfm.playFabId).subscribe(_ => {
                this.accountInfoLabel.string = `${udm.displayName.value}(${pfm.playFabId.value})`;
            }),
            MergeASAP(lm.flowStatus, gm.diffX2).subscribe(this.refeshButtons.bind(this)),
            nc.subscribe('fly_coin_inc_value', this.flyCoinIncValue.bind(this)),
        ];
    }

    adaptive() {
        this.topNode.setScale(v3(Vec3.ONE).multiplyScalar(lm.getAdaptiveScale()));
    }

    onDestroyView(): void {
        nullifySubscription.call(this, '_sub_coin_value_tween');
    }

    _sub_coin_value_tween: Subscription = null;
    refreshCoinTarget() {
        if (udm.temp_coin_diff.value != null) {
            this._sub_coin_value_tween = TweenToStart(this.coinValue, .4, { value: this.coinValue.value + udm.temp_coin_diff.value }).subscribe();
            return;
        }
        if (gm.coinAnimatingFlags.size > 0) return;
        nullifySubscription.call(this, '_sub_coin_value_tween');
        this._sub_coin_value_tween = TweenToStart(this.coinValue, .4, { value: udm.coin.value }).subscribe();
        // this.coinValue.value = udm.coin.value;
    }

    refreshHeart() {
        if (gm.heartAnimatingFlags.size > 0) return;
        this.heartValueLabel.string = `${udm.getHeartCount()}`;
        let remainMsInfHeart = udm.getRemainMsToOverInfHeart();
        if (remainMsInfHeart > 0) { // 在无限体力状态下
            this.heartCountLabel.string = `${MSRToString_th_m_s_2(MSResolve(remainMsInfHeart))}`;
            this.infHeartIconNode.active = true;
        } else {
            this.infHeartIconNode.active = false;
            let remainMs = udm.getRemainMsToRecoverOneHeart();
            if (remainMs != null) {
                let msr = MSResolve(remainMs);
                this.heartCountLabel.string = `${MSRToString_tm_s(msr)}`;
            } else {
                this.heartCountLabel.string = `MAX`;
            }
        }
    }

    refreshCoin() {
        this.coinCountLabel.string = StringTools.toKDotString(Math.floor(this.coinValue.value));
    }

    // refreshItems() {
    //     if (gm.itemAnimatingFlags.size > 0) return;
    //     this.itemsLabel.string = `(${udm.itemSwapper.value}, ${udm.itemMagnet.value}, ${udm.itemBalloon.value})`;
    // }

    refreshNoAds() {
        let text = `NoAds: ${udm.isNoAds()}`;
        if (udm.noAds.value) text += '(forever)';
        let remainMs = udm.getRemainMsToOverNoAds();
        if (remainMs > 0) {
            let msr = MSResolve(remainMs);
            text += `(${MSRToString_tm_s(msr)})`;
        }
        this.noAdsLabel.string = text;
    }

    settingsButtonClicked() {
        SettingsPanel.StartProcess().subscribe();
    }

    heartButtonClicked() {
        if (udm.getRemainMsToOverInfHeart() > 0 || udm.getRemainMsToRecoverOneHeart() == null) { // 无限体力或满心
            // ShopPanel.StartProcess().subscribe();
            gm.lobbyScrollToShopCommand.execute();
        } else {
            BuyHeartPanel.StartProcess((panel: BuyHeartPanel) => {
                panel.openWay = 'Home';
            }).subscribe();
        }
    }

    coinButtonClicked() {
        // ShopPanel.StartProcess().subscribe();
        gm.lobbyScrollToShopCommand.execute();
    }

    refeshButtons() {
        if (lm.flowStatus.value == FlowStatus.Lobby) {
            let opacity = linearClamp(0, 540 / 2, 0, 255, gm.diffX2.value);
            this.buttonsNode.getComponent(UIOpacity).opacity = opacity;
        } else {
            this.buttonsNode.getComponent(UIOpacity).opacity = 0;
        }
    }

    _sub_coin_shake: Subscription = null;

    flyCoinIncValue(param: { value: number }) {
        this.coinValue.value += param.value;
        nullifySubscription.call(this, '_sub_coin_shake');
        this._sub_coin_shake = AnimationPlay(this.coinIconSprite.getComponent(Animation), 'icon_shake').subscribe();
    }
}

